package com.yunbiao.ybbusstopplate.ui.view

import android.content.Context
import android.graphics.Color
import android.media.MediaPlayer
import android.os.Handler
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.VideoView
import com.blankj.utilcode.util.UiMessageUtils
import com.yunbiao.ybbusstopplate.BuildConfig
import com.yunbiao.ybbusstopplate.base.Constants
import com.yunbiao.ybbusstopplate.bean.ResouceBean
import com.yunbiao.ybbusstopplate.doublescreen.AdvertView
import com.yunbiao.ybbusstopplate.play_sync.ClientSocket
import com.yunbiao.ybbusstopplate.play_sync.PlayVideoData
import com.yunbiao.ybbusstopplate.play_sync.ServerSocket
import com.yunbiao.ybbusstopplate.play_sync.SocketCallback
import com.yunbiao.ybbusstopplate.play_sync.SocketUtil
import com.yunbiao.ybbusstopplate.ui.activity.FlavorType
import com.yunbiao.ybbusstopplate.utils.BaseTimer
import com.yunbiao.ybbusstopplate.utils.BitmapRecycle
import com.yunbiao.ybbusstopplate.utils.FileTool
import com.yunbiao.ybbusstopplate.utils.GlideLoadUtils
import com.yunbiao.ybbusstopplate.utils.ScreenPikerUtils
import java.util.TimerTask

class AutoPlayView : FrameLayout{
     val TAG = "AutoPlayView"
    private var imageView:ImageView?=null
    private var videoView:VideoView?=null
    private var linearLayout:LinearLayout?=null

    private var resourceList:List<ResouceBean>?=null
    private var uiHandler:Handler?=null
    private var playRunnable:PlayRunnable?=null
    private var isPlay:Boolean=true
    private var playTime:Int=15
    private var bitmapRecycle:BitmapRecycle?=null

    private var baseTimer: BaseTimer? = null
    private var timerTask: TimerTask? = null
    private val PLAY_MAG_TIMER: Long = 5000
    private var playFilePath: String? = null
    private var playVideoData: PlayVideoData? = null
    private var socketMessage : SocketMessage? = null

    constructor(context: Context):super(context){
        initView()
    }

    private fun initView(){
        bitmapRecycle= BitmapRecycle()

        imageView=ImageView(context)
        imageView!!.scaleType=ImageView.ScaleType.FIT_XY

        videoView= MyVideoView(context)

        linearLayout= LinearLayout(context)
        linearLayout!!.setBackgroundColor(Color.parseColor("#000000"))

        var layoutParams=LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT)
        layoutParams.gravity=Gravity.CENTER

        var videoParams=LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)
        videoParams.gravity=Gravity.CENTER
        Log.d("videoParams", "videoParams: " + videoParams.toString())


        imageView?.visibility= View.GONE
        videoView?.visibility=View.GONE

        linearLayout!!.addView(videoView,videoParams)
        linearLayout!!.addView(imageView,layoutParams)

        initListener()

        uiHandler=Handler(context.mainLooper)
        playRunnable=PlayRunnable()

        addView(linearLayout,layoutParams)

        sendPosition()
    }

    private fun sendPosition() {

        if(ScreenPikerUtils.isMasterScreen()){
            baseTimer = BaseTimer()
            timerTask = object : TimerTask() {
                override fun run() {
                    if (videoView != null) {
                        val position = videoView!!.currentPosition
                        sendSubScreen(position)
                    }
                }
            }
            baseTimer!!.getTimer().schedule(timerTask, 3000, PLAY_MAG_TIMER)
        }
        if(ScreenPikerUtils.isSubScreen()){
           socketMessage = SocketMessage()
           ClientSocket.getInstance().setSocketCallback(socketMessage)
        }

    }


    private fun initListener(){
        //加载成功
        videoView!!.setOnPreparedListener(object :MediaPlayer.OnPreparedListener{
            override fun onPrepared(p0: MediaPlayer?) {
                p0!!.start()
                p0.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT)
                Log.d("data", " start play")
            }
        })
        //播放完成
        videoView!!.setOnCompletionListener(object :MediaPlayer.OnCompletionListener{
            override fun onCompletion(p0: MediaPlayer?) {
                Log.d("data", " play over")
                playFilePath = null
                if (resourceList!!.size>=1){
                    Log.d("data", " play over if")
                    uiHandler!!.postDelayed(playRunnable!!,100)

                }else{
                    p0!!.start()
                }
            }
        })
        //播放出错
        videoView!!.setOnErrorListener(object :MediaPlayer.OnErrorListener{
            override fun onError(p0: MediaPlayer?, p1: Int, p2: Int): Boolean {
                if (resourceList!!.size>=1){
                    uiHandler!!.postDelayed(playRunnable!!,100)
                }
                return true
            }
        })
    }

    fun start(resourceList:List<ResouceBean>){
        this.resourceList=resourceList
        if (resourceList==null||resourceList.isEmpty()){
            return
        }
        isPlay=true
        uiHandler!!.post(playRunnable!!)
    }

    fun stop(){
        isPlay=false
        if (uiHandler!=null&&playRunnable!=null){
            uiHandler!!.removeCallbacks(playRunnable!!)
        }
    }

    fun destry(){
        UiMessageUtils.getInstance().send(AdvertView.DESTROY);
        isPlay=false
        if (uiHandler!=null&&playRunnable!=null){
            uiHandler!!.removeCallbacks(playRunnable!!)
        }
        if (videoView!=null){
            videoView!!.destroyDrawingCache()
            videoView!!.visibility= View.GONE
        }
    }
    var count:Int=0
    //匿名内部类
    inner class PlayRunnable:Runnable{
        override fun run() {
            if (!isPlay){
                return
            }
            // 这里如果是三分屏，临时使用中部的第一个文件作为底部播放文件，后面可改
            if (BuildConfig.FLAVOR_TYPE == FlavorType.IS_THREE_AREA) {
                if (resourceList!!.size>=2){
                    count=1
                }else{
                    count=0
                }
            }else if (count>=resourceList!!.size){
                count=0
            }
            val resource = resourceList!!.get(count)
            if (resource.type==FileTool.FileType.VIDEO){
                playVideo(resource.path)
            }else{

                var resourcePath = resource.path

                Log.d("net", "暂时 默认 中部广告: " + resourcePath)
//                // 中部广告 资源位置
//                resourcePath = Constants.advertCenterResourcePath

                playImage(resourcePath)
                Log.e(TAG, "run: ----------resource.path---------------->"+resource.path )

                if (resourceList!!.size>1){
                    if (resource.playTime!=0){
                        uiHandler!!.postDelayed(playRunnable!!,resource.playTime*1000L)
                    }else{
                        uiHandler!!.postDelayed(playRunnable!!,playTime*1000L)
                    }

                }
            }
            count++
        }
    }

    private fun playImage(path:String){
        GlideLoadUtils.getInstance().loadLocalImage(context,path,imageView,linearLayout,"0",bitmapRecycle)
        videoView!!.visibility= View.GONE
        imageView!!.visibility=View.VISIBLE
        UiMessageUtils.getInstance().send(AdvertView.IMAGE,path)
    }

    private fun playVideo(path:String){
        videoView!!.setVideoPath(path)
        imageView!!.visibility= View.GONE
        linearLayout!!.setBackgroundColor(Color.parseColor("#000000"))
        videoView!!.visibility=View.VISIBLE
        videoView!!.setZOrderOnTop(true)
        UiMessageUtils.getInstance().send(AdvertView.VIDEO,path)
        playFilePath = path
    }

    private fun playByMessage(playVideoData: PlayVideoData){

      //  Log.e(TAG, "playVideo:"+path )
        this.playVideoData = playVideoData
        if(videoView!!.visibility==View.GONE) {
            videoView!!.setVideoPath(playVideoData.filePath)
            imageView!!.visibility = View.GONE
            linearLayout!!.setBackgroundColor(Color.parseColor("#000000"))
            videoView!!.visibility = View.VISIBLE
            videoView!!.setZOrderOnTop(true)
            UiMessageUtils.getInstance().send(AdvertView.VIDEO, playVideoData.filePath)
            videoView!!.setOnErrorListener { mp: MediaPlayer?, what: Int, extra: Int -> true }
        }

        if (playVideoData.position != 0) {
            if (SocketUtil.isSamePosition(playVideoData.position, videoView!!.getCurrentPosition())) {
                return
            }
        }else{
            if(playFilePath.equals(playVideoData.filePath))
            return
        }
        playFilePath = playVideoData.filePath
        Log.d(TAG, "播放进度：" + "主屏幕进度：" + playVideoData.position + "," + "副屏幕进度：" + videoView!!.getCurrentPosition())
        videoView!!.setVideoPath(playFilePath)
        videoView!!.seekTo(playVideoData.position+10 )
        videoView!!.start()
//        videoView!!.setOnPreparedListener { mp ->
//            mp.start() // 开始播放视频
//            mp.seekTo(playVideoData.position) // 跳转到指定位置
//        }
//        videoView!!.setVideoPath(playFilePath) // 设置视频源路径
    }

    override fun onDetachedFromWindow() {
        destry()
        super.onDetachedFromWindow()
    }

    /**
     * 发消息给副屏
     * @param position
     */
    private fun sendSubScreen(position: Int) {
        if (playFilePath != null) {
            val data: String = SocketUtil.getPlayData(playFilePath, position,0)
            ServerSocket.getInstance().send(data)
        }
    }

    inner class SocketMessage : SocketCallback {
        override fun receiveMessage(action: Int, `object`: Any) {
            if (action == 1) {
                 Log.d(TAG, "通知副屏播放" );
                val playVideoData: PlayVideoData = `object` as PlayVideoData
                playByMessage(playVideoData)
            }
        }
    }

}


